package cn.itcast.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieDemo01 extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//	    1.提示信息 ; 

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		PrintWriter out = response.getWriter();
		
		out.print("<a href='/day07/CookieDemo02'>清除访问时间</a><br/>");
		out.write("你上次访问的时间是 : ");




		//		2.或得用户时间 cookies

		Cookie[] cookies = request.getCookies();

		for (int i = 0; cookies!=null && i < cookies.length; i++) {

			if (cookies[i].getName() != null&& "lastAccessTime".equals(cookies[i].getName())  ) {

				String cookieValue = cookies[i].getValue();
				long lcookieValue  = Long.parseLong(cookieValue);
				Date date = new Date(lcookieValue);	

				out.write(date.toLocaleString());

			}

		}

		//		3.给用户回送最新的访问时间
		Cookie cookie = new Cookie("lastAccessTime", System.currentTimeMillis()+"");
		cookie.setMaxAge(1*30*24*3600);
		cookie.setPath("/day07");
		response.addCookie(cookie);




	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);

	}

}
